<!--
  * 供应商管理列表
  *
  * @Author:    1024创新实验室
  * @Date:      2024-07-19 20:30:00
  * @Wechat:    zhuoda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row" v-privilege="'purchase:supplier:query'">
      <a-form-item label="供应商编码" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.supplierCode" placeholder="供应商编码" />
      </a-form-item>

      <a-form-item label="供应商名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.supplierName" placeholder="供应商名称" />
      </a-form-item>

      <a-form-item label="供应商类型" class="smart-query-form-item">
        <SmartEnumSelect enum-name="SUPPLIER_TYPE_ENUM" v-model:value="queryForm.supplierType" width="120px" />
      </a-form-item>

      <a-form-item label="联系人" class="smart-query-form-item">
        <a-input style="width: 150px" v-model:value="queryForm.contactPerson" placeholder="联系人" />
      </a-form-item>

      <a-form-item label="联系电话" class="smart-query-form-item">
        <a-input style="width: 150px" v-model:value="queryForm.contactPhone" placeholder="联系电话" />
      </a-form-item>

      <a-form-item label="信用等级" class="smart-query-form-item">
        <SmartEnumSelect enum-name="SUPPLIER_CREDIT_RATING_ENUM" v-model:value="queryForm.creditRating" width="120px" />
      </a-form-item>

      <a-form-item label="状态" class="smart-query-form-item">
        <SmartEnumSelect enum-name="SUPPLIER_STATUS_ENUM" v-model:value="queryForm.status" width="120px" />
      </a-form-item>

      <a-form-item label="创建时间" class="smart-query-form-item">
        <a-range-picker 
          v-model:value="createTimeRange" 
          :allowClear="true" 
          value-format="YYYY-MM-DD"
          @change="onCreateTimeChange"
        />
      </a-form-item>

      <a-form-item class="smart-query-form-item">
        <a-button-group>
          <a-button type="primary" @click="onSearch" v-privilege="'purchase:supplier:query'">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" v-privilege="'purchase:supplier:query'">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="addSupplier" type="primary" v-privilege="'purchase:supplier:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="confirmBatchDelete" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'purchase:supplier:batchDelete'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.PURCHASE.SUPPLIER" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="supplierId"
      :scroll="{ x: 1200, y: yHeight }"
      bordered
      :pagination="false"
      :showSorterTooltip="false"
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      @change="onChange"
      @resizeColumn="handleResizeColumn"
    >
      <template #headerCell="{ column }">
        <SmartHeaderCell v-model:value="queryForm[column.filterOptions?.key || column.dataIndex]" :column="column" @change="queryData" />
      </template>
      
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'supplierTypeDesc'">
          <a-tag :color="getSupplierTypeColor(record.supplierType)">{{ text }}</a-tag>
        </template>
        
        <template v-if="column.dataIndex === 'creditRatingDesc'">
          <a-tag :color="getCreditRatingColor(record.creditRating)">{{ text }}</a-tag>
        </template>
        
        <template v-if="column.dataIndex === 'statusDesc'">
          <a-tag :color="getStatusColor(record.status)">{{ text }}</a-tag>
        </template>
        
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="viewSupplier(record)" type="link" size="small">详情</a-button>
            <a-button @click="editSupplier(record)" type="link" size="small" v-privilege="'purchase:supplier:update'">编辑</a-button>
            <a-dropdown>
              <template #overlay>
                <a-menu>
                  <a-menu-item v-if="record.status === 1" v-privilege="'purchase:supplier:updateStatus'">
                    <a @click="updateStatus(record, 0)">禁用</a>
                  </a-menu-item>
                  <a-menu-item v-if="record.status === 0" v-privilege="'purchase:supplier:updateStatus'">
                    <a @click="updateStatus(record, 1)">启用</a>
                  </a-menu-item>
                  <a-menu-item v-privilege="'purchase:supplier:delete'">
                    <a @click="deleteSupplier(record)" style="color: red">删除</a>
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button type="link" size="small">
                更多 <DownOutlined />
              </a-button>
            </a-dropdown>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <!-- 供应商表单弹窗 -->
    <SupplierFormModal ref="formModal" @reloadList="queryData" />
  </a-card>
</template>

<script setup>
  import SupplierFormModal from './components/supplier-form-modal.vue';
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { supplierApi } from '/@/api/business/purchase/supplier/supplier-api';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
  import _ from 'lodash';
  import SmartHeaderCell from '/@/components/support/table-header-cell/index.vue';
  import { SUPPLIER_TYPE_ENUM, SUPPLIER_STATUS_ENUM, SUPPLIER_CREDIT_RATING_ENUM } from '/@/constants/business/purchase/supplier-const';

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '供应商编码',
      dataIndex: 'supplierCode',
      resizable: true,
      filterOptions: {
        type: 'input',
        key: 'supplierCode',
      },
      width: 150,
    },
    {
      title: '供应商名称',
      dataIndex: 'supplierName',
      resizable: true,
      filterOptions: {
        type: 'input',
        key: 'supplierName',
      },
      width: 200,
    },
    {
      title: '供应商类型',
      dataIndex: 'supplierTypeDesc',
      resizable: true,
      filterOptions: {
        type: 'enum-select',
        enumName: 'SUPPLIER_TYPE_ENUM',
        key: 'supplierType',
      },
      width: 120,
    },
    {
      title: '联系人',
      dataIndex: 'contactPerson',
      resizable: true,
      filterOptions: {
        type: 'input',
        key: 'contactPerson',
      },
      width: 120,
    },
    {
      title: '联系电话',
      dataIndex: 'contactPhone',
      resizable: true,
      filterOptions: {
        type: 'input',
        key: 'contactPhone',
      },
      width: 150,
    },
    {
      title: '联系邮箱',
      dataIndex: 'contactEmail',
      resizable: true,
      ellipsis: true,
      width: 200,
    },
    {
      title: '信用等级',
      dataIndex: 'creditRatingDesc',
      resizable: true,
      filterOptions: {
        type: 'enum-select',
        enumName: 'SUPPLIER_CREDIT_RATING_ENUM',
        key: 'creditRating',
      },
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'statusDesc',
      resizable: true,
      filterOptions: {
        type: 'enum-select',
        enumName: 'SUPPLIER_STATUS_ENUM',
        key: 'status',
      },
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      resizable: true,
      width: 150,
    },
    {
      title: '操作',
      dataIndex: 'action',
      resizable: true,
      fixed: 'right',
      width: 150,
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    supplierCode: '',
    supplierName: '',
    supplierType: undefined,
    contactPerson: '',
    contactPhone: '',
    creditRating: undefined,
    status: undefined,
    createTimeBegin: '',
    createTimeEnd: '',
    pageNum: 1,
    pageSize: 10,
    sortItemList: [],
  };

  const queryForm = reactive({ ...queryFormState });
  const tableData = ref([]);
  const total = ref(0);
  const selectedRowKeyList = ref([]);
  const createTimeRange = ref([]);

  // 查询数据
  async function queryData() {
    tableData.value = [];
    try {
      SmartLoading.show();
      // 确保分页参数是数字类型
      const params = {
        ...queryForm,
        pageNum: Number(queryForm.pageNum) || 1,
        pageSize: Number(queryForm.pageSize) || 10
      };
      console.log('查询参数:', JSON.stringify(params, null, 2));
      const queryResult = await supplierApi.queryPage(params);
      const list = queryResult.data.list || [];
      total.value = queryResult.data.total;
      tableData.value = list;
    } catch (e) {
      console.error('查询错误:', e);
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // 重置查询条件
  function resetQuery() {
    Object.assign(queryForm, queryFormState);
    createTimeRange.value = [];
    queryData();
  }

  // 查询
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 创建时间范围改变
  function onCreateTimeChange(dates) {
    if (dates && dates.length === 2) {
      queryForm.createTimeBegin = dates[0];
      queryForm.createTimeEnd = dates[1];
    } else {
      queryForm.createTimeBegin = '';
      queryForm.createTimeEnd = '';
    }
  }

  // 表格change事件
  function onChange(pagination, filters, sorter) {
    let sortList = [];
    if (Array.isArray(sorter)) {
      sortList = sorter.filter((item) => item.order).map((item) => ({ column: item.field, asc: item.order === 'ascend' }));
    } else {
      if (sorter.order) {
        sortList.push({ column: sorter.field, asc: sorter.order === 'ascend' });
      }
    }
    queryForm.sortItemList = sortList;
    queryData();
  }

  // 选择表格行
  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  // ---------------------------- 添加/编辑 ----------------------------

  const formModal = ref();

  function addSupplier() {
    formModal.value.showModal();
  }

  function editSupplier(data) {
    formModal.value.showModal(data);
  }

  function viewSupplier(data) {
    formModal.value.showModal(data, true);
  }

  // ---------------------------- 删除 ----------------------------

  function deleteSupplier(data) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该供应商吗？',
      okText: '删除',
      okType: 'danger',
      onOk() {
        return deleteRequest(data.supplierId);
      },
    });
  }

  function confirmBatchDelete() {
    if (selectedRowKeyList.value.length <= 0) {
      message.warning('请选择要删除的供应商');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的供应商吗？',
      okText: '删除',
      okType: 'danger',
      onOk() {
        return batchDelete();
      },
    });
  }

  async function deleteRequest(supplierId) {
    try {
      SmartLoading.show();
      await supplierApi.delete(supplierId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  async function batchDelete() {
    try {
      SmartLoading.show();
      const promises = selectedRowKeyList.value.map(id => supplierApi.delete(id));
      await Promise.all(promises);
      message.success('批量删除成功');
      selectedRowKeyList.value = [];
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 状态更新 ----------------------------

  async function updateStatus(record, status) {
    try {
      SmartLoading.show();
      await supplierApi.updateStatus(record.supplierId, status);
      message.success('状态更新成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 其他 ----------------------------

  // 获取供应商类型颜色
  function getSupplierTypeColor(type) {
    const typeEnum = Object.values(SUPPLIER_TYPE_ENUM).find(item => item.value === type);
    return typeEnum?.color || 'default';
  }

  // 获取信用等级颜色
  function getCreditRatingColor(rating) {
    const ratingEnum = Object.values(SUPPLIER_CREDIT_RATING_ENUM).find(item => item.value === rating);
    return ratingEnum?.color || 'default';
  }

  // 获取状态颜色
  function getStatusColor(status) {
    const statusEnum = Object.values(SUPPLIER_STATUS_ENUM).find(item => item.value === status);
    return statusEnum?.color || 'default';
  }

  // 表格高度
  const yHeight = ref(600);

  function handleResizeColumn(w, col) {
    col.width = w;
  }

  onMounted(() => {
    queryData();
  });
</script>

<style scoped>
  .smart-table-operate {
    display: flex;
    align-items: center;
    gap: 8px;
  }
</style>